package com.thinkit.security.login;
import com.thinkit.core.constant.Constants;
import com.thinkit.nosql.base.BaseRedisService;
import com.thinkit.security.custom.CustomRiskCheckBase;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

public class PlatLoginCheckerExecutor extends CustomRiskCheckBase implements LoginChecker  {

    private UserDetailsService userDetailsService;

    private BaseRedisService baseRedisService;

    private String userAccount;

    private String userPassword;

    private String clientId;

    private BCryptPasswordEncoder bCryptPasswordEncoder;;


    public PlatLoginCheckerExecutor(String userAccount, String userPassword){
       this.userAccount=userAccount;
       this.userPassword=userPassword;
    }

    public PlatLoginCheckerExecutor(String userAccount, String userPassword,String clientId){
        this.userAccount=userAccount;
        this.userPassword=userPassword;
        this.clientId = clientId;
    }

    @Override
    public UserDetails login() {
        UserDetails userDetails;
        try {
            userDetails=userDetailsService.loadUserByUsername(userAccount);
        }catch (Exception e){
            throw e;
        }
        if (!bCryptPasswordEncoder.matches(userPassword, userDetails.getPassword())) {
            throw new UsernameNotFoundException("账号或密码不正确!");
        }
        return userDetails;
    }

    @Override
    public void loginSuccess(UserDetails userDetails,String userAccount) {
        clearErrorLog(clientId+ Constants.DOT+userAccount);
    }

    @Override
    public void loginFail(UserDetails userDetails,String userAccount) {
        writeErrorLog(clientId+ Constants.DOT+userAccount);
    }

    @Override
    public LoginChecker build(UserDetailsService userDetailsService, BCryptPasswordEncoder bCryptPasswordEncoder, BaseRedisService baseRedisService) {
        this.userDetailsService = userDetailsService;
        this.bCryptPasswordEncoder = bCryptPasswordEncoder;
        this.baseRedisService = baseRedisService;
        initRedis(baseRedisService);
        return this;
    }
}
